package paolo.android.bookloc;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;


public class DetailForm extends Activity {
	EditText name = null;
	EditText address = null;
	EditText notes = null;
	RadioGroup types = null;
	Location current = null;
	
	String locationId = null;
	SQLiteDatabase db = null;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_form);
		
		db = (new LocationSQLiteHelper(this)).getWritableDatabase();

		name = (EditText)findViewById(R.id.name);
		address = (EditText)findViewById(R.id.addr);
		notes = (EditText)findViewById(R.id.notes);
		types = (RadioGroup)findViewById(R.id.types);
		Button save = (Button)findViewById(R.id.save);
		save.setOnClickListener(onSave);
		
		locationId = getIntent().getStringExtra(BookLoc.ID_EXTRA);
		
		if (locationId == null) {
			current = new Location();
		}
		else {
			load();
		}
		
		if (savedInstanceState != null) {
			name.setText(savedInstanceState.getString("name"));
			address.setText(savedInstanceState.getString("address"));
			notes.setText(savedInstanceState.getString("notes"));
			types.check(savedInstanceState.getInt("type"));
		}	
	}

	private View.OnClickListener onSave=new View.OnClickListener() {
		public void onClick(View v) {
			current.setName(name.getText().toString());
			current.setAddress(address.getText().toString());
			current.setNotes(notes.getText().toString());
			
			switch (types.getCheckedRadioButtonId()) {
			case R.id.food:
				current.setType("food");
				break;
			case R.id.store:
				current.setType("store");
				break;
			case R.id.person:
				current.setType("person");
				break;
			}
			
			if (locationId == null) {
				current.save(db);
			}
			else {
				current.update(locationId, db);
			}
			
			finish();
		}
	};
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		db.close();
	}
	
	private void load() {
		current = Location.getById(locationId, db);
		
		name.setText(current.getName());
		address.setText(current.getAddress());
		
		if (current.getType().equals("store")) {
			types.check(R.id.store);
		}
		else if (current.getType().equals("food")) {
			types.check(R.id.food);
		}
		else {
			types.check(R.id.person);
		}
		
		notes.setText(current.getNotes());
	}
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		
		savedInstanceState.putString("name", name.getText().toString());
		savedInstanceState.putString("address", address.getText().toString());
		savedInstanceState.putString("notes", notes.getText().toString());
		savedInstanceState.putInt("type", types.getCheckedRadioButtonId());

	}

}